package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.Service.UserService;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取username,去User表查询，
        if(username == null){
            return null;
        }
        //调用用户服务（底层基于Dubbo实现远程调用）获取用户信息
        User user = userService.findByUsername(username);
        List<SimpleGrantedAuthority> list = new ArrayList<>();//收集该user的角色和权限
        if(user != null){
            //获取角色
            Set<Role> roles = user.getRoles();
            if(roles != null && roles.size() > 0){
                for (Role role : roles) {
                    String keyword = role.getKeyword();//角色关键字，角色表示
                    list.add(new SimpleGrantedAuthority(keyword));
                    Set<Permission> permissions = role.getPermissions();
                    if(permissions != null && permissions.size() >0){
                        for (Permission permission : permissions) {
                            list.add(new SimpleGrantedAuthority(permission.getKeyword()));//权限关键字，权限标识
                        }
                    }
                }

            }
        }
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
